<?php
namespace app\common\logic;

use think\facade\Db;
use think\facade\Session;

class AdminLogic
{

    public function encrypt($str,$ec_salt){
        return md5($str.$ec_salt);
    }

    public function login($username, $password,$type)
    {
        if (empty($username) || empty($password)) {
            return ['errcode' => 0, 'message' => '请填写账号密码'];
        }
        $info = Db::name('admin')->where('username','=',$username)->find();
        if(!$info){
            return ['errcode' => 0, 'message' => '没有这个用户'];
        }

        $condition['a.username'] = $username;
        $condition['a.password'] = $this->encrypt($password,$info['ec_salt']);

        $field = 'a.admin_id,a.username,a.last_login,a.last_ip,a.is_open as a_is_open';
        $field .= ',ar.act_list,ar.is_open as ar_is_open';

        $admin = Db::name('admin')
                 ->alias('a')
                 ->join('admin_role ar', 'a.role_id=ar.role_id')
                 ->field($field)
                 ->where($condition)
                 ->find();

        if (!$admin) {
            return ['errcode' => 0, 'message' => '账号密码不正确'];
        }
        if($admin['ar_is_open']==0){
            return ['errcode' => 0, 'message' => '角色已禁用，请联系管理员'];
        }
        if($admin['a_is_open']==0){
            return ['errcode' => 0, 'message' => '账号已禁用，请联系管理员'];
        }

        if($type == 1) {
            $this->handleLogin($admin, $admin['act_list']);
        }

        $url = url('Index/index');
        return ['errcode' => 1,'message' => '登录成功', 'dyurl' => $url];
    }

    public function handleLogin($admin, $actList)
    {
        $ip = request()->ip();
        Db::name('admin')->where('admin_id', $admin['admin_id'])->save([
            'last_login' => time(),
            'last_ip' => $ip
        ]);

        Session::set('act_list', $actList);
        Session::set('admin_user', $admin['username']);
        Session::set('admin_id', $admin['admin_id']);
        Session::set('last_login_time', $admin['last_login']);
        Session::set('last_login_ip', $admin['last_ip']);
        \think\facade\Session::save();

        adminLog("用户登录，用户名：".$admin['username']."，登录IP：".$ip,$admin['admin_id']);
    }

    public function logout($adminId)
    {
        $ip = request()->ip();
        $admin = Db::name('admin')->where('admin_id', $adminId)->find();
        adminLog("用户退出，用户名：".$admin['username']."，登录IP：".$ip,$adminId);

        session_unset();
        session(null);
        \think\facade\Session::clear();

        cookie('workspaceParam',null);
    }
}
